<script setup lang="ts">
// import { ImagePreviewGroup, Image } from 'ant-design-vue'
import { ref, watch } from "vue";
import { onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { isEmpty } from "lodash";
import { getToken } from "@/utils/auth";
import { listVehicles, listVehiclesleft, searchVehicles } from "@/apis/vehicles";
import { getProduct } from "@/apis/products";
import { decrypt } from "@/utils/encrypt";
import VehicleTree, { VehicleTreeChildren } from "@/components/vehicle_tree/index.vue";
// import VehicleTreeL, { VehicleTreeChildren } from "@/components/vehicle_treeL/index.vue";

import GuideSelect from "@/components/guide_select/index.vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";
const router = useRouter();
import routers from "@/router"; // 导入路由实例
const userProfile = ref<{ userId?: string; collect?: any[] }>({});
const isLoggedin = ref(false);
const showLoginPrompt = ref(false); //登录弹窗
const showNullPrompt = ref(false); //车型无数据弹窗

let isadmin = 0; //定义 isadmin 变量

// 从 localStorage 中获取 isadmin 的值
const storedUserData = localStorage.getItem("userData");
if (storedUserData) {
  const loginData = JSON.parse(storedUserData);
  if (loginData && loginData.isAdmin) {
    isadmin = loginData.isAdmin;
    // console.log("是否管理员:", isadmin);
  }
}
const route = useRoute(); // 使用 useRoute 来获取 route 实例
// 左舵还是右舵
const vehicleType = ref("");

onMounted(() => {
  // 确保 route.query.from 是一个字符串
  if (typeof route.query.from === "string") {
    vehicleType.value = route.query.from;
    // console.log("从路由传递过来的 from 参数:", vehicleType.value);
  } else {
    vehicleType.value = ""; // 如果不是字符串，赋空字符串或其他默认值
  }
  loadVideo(); // 在组件加载完毕后加载视频
});

// 产品类型
const productOptions = ref<any[]>([
  {
    value: "6",
    payload: {
      typeId: "6",
      typeName: "全包围脚垫",
      typeENName: "Car Mat",
    },
  },
]);

// 当前选中产品类型
const selectProduct = ref<string>(productOptions.value.at(0).value);
/**
 * 获取用户信息.
 */
async function getUserProfile() {
  const token = getToken();
  if (isEmpty(token)) {
    showLoginPrompt.value = true; // 如果未登录，显示登录提示框
    return;
  }

  const userId = decrypt(token!);
  if (userId) {
    isLoggedin.value = true; // 如果已登录，设置isLoggedin为true
    userProfile.value.userId = userId;
  }
}
function handleLogin() {
  routers.push({ name: "SignIn" }); // 使用路由跳转到登录页面
}
// 定义关闭弹窗的方法
function closePopup() {
  showLoginPrompt.value = false;
}
function closeNullCx() {
  showNullPrompt.value = false;
}
// 车型查询条件
const queryData = ref({
  productId: selectProduct.value,
  carId: "",
  pageIndex: 1,
  pageSize: 20,
});

// 车型数据
const vehicles = ref<any[]>([]);

// 数据总量
const total = ref(0);

// 顶部面包屑
const breadcrumbs = ref<string[]>([productOptions.value.at(0).payload.typeName]);

// 找车向导选项
const vehicleGuides = ref<string[][]>([]);
const vehicleGuidesDict = ref<Record<string, string>>({});

// 当前选中向导
const selectGuide = ref<string[]>([]);

// 当前产品视频
const currentProduct = ref<any>(null);

// const currentProduct = ref<{
//     coverPicUrl: string;
//     id: string;
//     text: string;
// } | null>(null);

// 搜索关键字
const keyword = ref("");
const searchKeyword = ref(0);
watch(selectProduct, (val: any) => {
  queryData.value.pageIndex = 1;
  queryData.value.pageSize = 20;
  queryData.value.productId = val;

  const _product = productOptions.value.find((p: { value: any }) => p.value === val);
  breadcrumbs.value.splice(0, breadcrumbs.value.length, _product.payload.typeName);
});

// 定义一个函数来检查对象是否为空
function isEmptyObject(obj: any): boolean {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      return false;
    }
  }
  return true;
}
//车行树点击后获取车型图片
watch(queryData.value, async (val: any) => {
  // console.log("整整整");
  try {
    // console.log(vehicleType.value);
    const apiFunction = vehicleType.value === "left" ? listVehiclesleft : listVehicles;
    const { data, totalCount }: { data: any[]; totalCount: number } = await apiFunction({
      data: {
        ...val,
        isAdmin: isadmin, // 将 isadmin 是否为管理员添加到请求参数中
      },
    });
    // console.log("点击车型打印 data:", data);

    selectGuide.value = [];
    if (data && Array.isArray(data)) {
      vehicleGuides.value = data.map((e) => e.listDesc);
      vehicleGuidesDict.value = mergedArray(
        data.map((e) => e.listDesc),
        data.map((e) => e.listDesc_En)
      );
      // 对每个车辆的图片进行处理
      data.forEach((vehicle) => {
        const picimg: string[] = [];
        if (vehicle.picUrl) {
          const picUrlImages = vehicle.picUrl
            .split(",")
            .map((image: string) => image.trim());
          if (picUrlImages.length > 0) {
            picimg.push(picUrlImages[0]); // 把picUrl 中的第一张图片放到 picimg 数组的第一个位置
          }
        }

        if (vehicle.picList && !isEmptyObject(vehicle.picList)) {
          const { otherPicList } = vehicle.picList;
          //   if (carGongYiTuList) {
          //     carGongYiTuList.forEach((item: any) => {
          //       if (item.imageUrl) {
          //         picimg.push(item.imageUrl);
          //       }
          //     });
          //   }
          if (otherPicList) {
            otherPicList.forEach((item: any) => {
              if (item.imageUrl) {
                picimg.push(item.imageUrl);
              }
            });
          }
        }

        vehicle.images =
          picimg.length > 0
            ? picimg
            : vehicle.picUrl
            ? vehicle.picUrl.split(",").map((image: string) => image.trim())
            : [];
      });
      vehicles.value = data;
      // console.log("车辆车型图数据", vehicles.value.length);
      total.value = totalCount;
      showVideo.value = false;
    }
  } catch (err) {
    console.error(err);
  }
});

async function getProductVideo() {
  try {
    // 根据选择的左右类型（左舵或右舵）设置 type 参数
    const type = vehicleType.value === "left" ? 0 : 1;
    const { data } = await getProduct({
      data: {
        productType: selectProduct.value,
        type: type,
      },
    });
    currentProduct.value = data;
  } catch (error) {
    // console.error("获取产品数据失败", error);
  }
}

function mergedArray(first: string[][], second: string[][]) {
  const mappedObject = {};
  for (let i = 0; i < first.length; i++) {
    const keyArray = first[i];
    const valueArray = second[i];
    keyArray.forEach((keyElement, index) => {
      const valueElement = valueArray[index];
      if (!(keyElement in mappedObject)) {
        (mappedObject as Record<string, string>)[keyElement] = valueElement;
      }
    });
  }
  return mappedObject;
}

/**
 * 搜索按钮点击事件.
 */
async function handleSearch() {
  try {
    const { data, totalCount } = await searchVehicles({
      data: {
        productId: queryData.value.productId,
        carCode: keyword.value,
      },
    });
    if (data.length > 0) {
      vehicles.value = data;
      // console.log("搜出来的", vehicles.value);
      searchKeyword.value = data[0].carStructId;
      // console.log("searchKeyword", searchKeyword.value);
      total.value = totalCount;
      selectGuide.value = [];
      if (data && Array.isArray(data)) {
        vehicleGuides.value = data.map((e) => e.listDesc);
        vehicleGuidesDict.value = mergedArray(
          data.map((e) => e.listDesc),
          data.map((e) => e.listDesc_En)
        );
        // 对每个车辆的图片进行处理
        data.forEach((vehicle) => {
          const picimg: string[] = [];
          if (vehicle.picUrl) {
            const picUrlImages = vehicle.picUrl
              .split(",")
              .map((image: string) => image.trim());
            if (picUrlImages.length > 0) {
              picimg.push(picUrlImages[0]); // 把picUrl 中的第一张图片放到 picimg 数组的第一个位置
            }
          }

          if (vehicle.picList && !isEmptyObject(vehicle.picList)) {
            const { otherPicList } = vehicle.picList;
            //   if (carGongYiTuList) {
            //     carGongYiTuList.forEach((item: any) => {
            //       if (item.imageUrl) {
            //         picimg.push(item.imageUrl);
            //       }
            //     });
            //   }
            if (otherPicList) {
              otherPicList.forEach((item: any) => {
                if (item.imageUrl) {
                  picimg.push(item.imageUrl);
                }
              });
            }
          }

          vehicle.images =
            picimg.length > 0
              ? picimg
              : vehicle.picUrl
              ? vehicle.picUrl.split(",").map((image: string) => image.trim())
              : [];
        });
        vehicles.value = data;
        // console.log("车辆车型图数据", vehicles.value.length);
        total.value = totalCount;
        showVideo.value = false;
        // 在此处重新设置 VehicleTree 组件的 searchKeyword 属性
        // 更新 searchKeyword 状态
        // searchKeyword.value = keyword.value;
      }
    } else {
      showNullPrompt.value = true; // 如车型无数据，显示无数据提示弹窗
    }
  } catch (err) {}
}

const showVideo = ref(true); // 默认在页面加载时显示视频

function loadVideo() {
  // console.log("视频223");
  // 当页面加载或点击面包屑时加载视频
  getProductVideo();
}

function handleBreadcrumbClick(index: number) {
  if (index !== 0) return;
  vehicles.value = [];
  loadVideo(); // 重新加载视频
  showVideo.value = true; // 确保点击面包屑时显示视频
}

/**
 * 产品点击事件.
 * @param value
 */
function handleProductClick(value: any) {
  getUserProfile().then(() => {
    if (isLoggedin.value) {
      const type = vehicleType.value === "left" ? 0 : 1;
      const path = router.resolve({
        name: "Details",
        query: {
          id: value.carPicId,
          productType: selectProduct.value,
          type: type,
          ancestors: breadcrumbs.value,
        },
      });
      window.open(path.href, "_blank");
    } else {
      showLoginPrompt.value = true; // 如果未登录，显示登录提示框
    }
  });
}

/**
 * 左侧车辆树形结构选择事件.
 * @param {VehicleTreeChildren} value
 */
function handleVehicleSelect(value: VehicleTreeChildren, ancestors: any[]) {
  breadcrumbs.value.splice(1, breadcrumbs.value.length, ...ancestors.map((e) => e.name));
  if (value?.id) {
    queryData.value.carId = value?.id;
  }
}
</script>

<template>
  <!-- 登录提示框 -->
  <div v-if="showLoginPrompt" class="fixed inset-0 z-50 flex items-center justify-center">
    <div class="fixed inset-0 bg-black opacity-50" @click="closePopup"></div>
    <!-- 为遮罩层添加点击事件 -->
    <!-- 遮罩层 -->
    <div
      class="p-6 bg-white rounded shadow"
      style="
        width: 14rem;
        height: 10rem;
        display: flex;
        flex-direction: column;
        font-size: 1.1rem;
        justify-content: center;
        align-items: center;
        z-index: 60;
      "
    >
      <p style="font-weight: 500">请登录以查看产品</p>
      <button
        @click="handleLogin"
        class="px-4 py-2 mt-4 text-white bg-blue-500 rounded"
        style="
          background-color: blue;
          border: none;
          margin-top: 1.5rem;
          cursor: pointer;
          padding: 0.5rem 1.5rem;
        "
      >
        去登录
      </button>
    </div>
  </div>
  <!-- 车型无数据弹窗 -->
  <div v-if="showNullPrompt" class="fixed inset-0 z-50 flex items-center justify-center">
    <div class="fixed inset-0 bg-black opacity-50" @click="closeNullCx"></div>
    <!-- 为遮罩层添加点击事件 -->
    <!-- 遮罩层 -->
    <div
      class="p-6 bg-white rounded shadow"
      style="
        width: 14rem;
        height: 10rem;
        display: flex;
        flex-direction: column;
        font-size: 1.1rem;
        justify-content: center;
        align-items: center;
        z-index: 60;
      "
    >
      <p style="font-weight: 500">该车型暂无数据哦</p>
      <button
        @click="closeNullCx"
        class="px-4 py-2 mt-4 text-white bg-blue-500 rounded"
        style="
          background-color: blue;
          border: none;
          margin-top: 1.5rem;
          cursor: pointer;
          padding: 0.5rem 1.5rem;
        "
      >
        关闭
      </button>
    </div>
  </div>
  <div
    class="flex h-full bg-gray-100"
    style="margin-left: 1.41666rem; margin-right: 2.41666rem"
  >
    <div class="flex-shrink-0 pt-6 bg-white widtts">
      <VehicleTree
        v-if="vehicleType !== ''"
        :productType="vehicleType"
        @on-select="handleVehicleSelect"
        :searchKeyword="searchKeyword"
      />
    </div>
    <div class="flex flex-col flex-1 right">
      <!-- <div class="px-12 py-3 bg-white border-0 border-b border-gray-200 border-solid">
        <a-segmented class="fill" v-model:value="selectProduct" :options="productOptions">
          <template #label="{ payload }">
            <span class="flex flex-col py-1">
              <strong class="text-sm">
                {{ payload.typeName }}
              </strong>
              <small class="text-xs text-gray-500">
                {{ payload.typeENName }}
              </small>
            </span>
          </template>
        </a-segmented>
      </div> -->

      <template v-if="!isEmpty(vehicles)">
        <div class="flex flex-col flex-shrink-0 productc">
          <div
            style="background-color: #e8ecf3; margin-left: 0.03rem"
            class="flex items-center justify-between py-1 pxma"
          >
            <a-breadcrumb separator="<">
              <template v-for="(item, index) in breadcrumbs" :key="item">
                <a-breadcrumb-item
                  :class="{
                    '!text-primary': index === 0,
                    'cursor-pointer': index === 0,
                  }"
                  @click="() => handleBreadcrumbClick(index)"
                  >{{ item }}</a-breadcrumb-item
                >
              </template>
            </a-breadcrumb>
            <div class="flex items-center gap-x-2" style="margin-left: 0.11458rem">
              <span>找车向导(Car guide): </span>
              <GuideSelect
                v-model="selectGuide"
                :options="vehicleGuides"
                :options-dict="vehicleGuidesDict"
              />
            </div>
            <a-input-search
              style="width: 20rem; position: absolute; right: 0"
              size="small"
              placeholder="输入车型编号 如: ADA6L01"
              v-model:value="keyword"
              @search="handleSearch"
            />
          </div>
        </div>
        <div class="flex-1 overflow-y-scroll leftcon overscroll-contain">
          <div class="grid justify-center grid-cols-1">
            <template
              v-for="vehicle in vehicles.filter((e) => {
                return selectGuide.length
                  ? selectGuide.every((guide) => e.listDesc?.includes(guide))
                  : true;
              })"
              :key="vehicle"
            >
              <a-card
                :bordered="false"
                :bodyStyle="{
                  position: 'elative',
                  padding: '0.5rem',
                  overflow: 'visible',
                }"
                class="mb-4"
              >
                <div
                  class="overflow-hidden flex-nowrap"
                  style="max-width: 100%; overflow-x: 100%"
                >
                  <div style="width: 100%">
                    <template v-if="vehicle.images && vehicle.images.length">
                      <a-image-preview-group>
                        <Swiper :slidesPerView="3">
                          <SwiperSlide
                            v-for="(image, index) in vehicle.images"
                            :key="index"
                            style="width: calc(30% - 1.8rem); margin-left: 0.026rem"
                          >
                            <a-image
                              class="flex-shrink-0 mr-2 rounded-md aimage"
                              :src="image.trim()"
                              style="height: 18rem; width: 23rem; object-fit: fill"
                            />
                          </SwiperSlide>
                        </Swiper>
                      </a-image-preview-group>
                    </template>
                  </div>
                </div>
                <div class="flex items-center mt-6">
                  <!-- 编号 -->
                  <small
                    class="text-sm text-gray-500 limited-text"
                    :title="vehicle.picNumber"
                  >
                    <div class="onxia">
                      <span> 编号</span>
                      <span>number</span>
                    </div>
                    <div class="bianhao">
                      {{ vehicle.picNumber }}
                    </div>
                  </small>

                  <!-- 工艺图按钮 -->
                  <a-button
                    class="text-sm leftlxx"
                    @click="() => handleProductClick(vehicle)"
                  >
                    <span>拼接示意图</span>
                    <span class="text-xs">Process Drawing</span>
                  </a-button>
                  <!-- 年份 -->
                  <small
                    class="text-sm text-gray-500 limited-text"
                    :title="vehicle.picNumber"
                    style="margin-left: 1.7rem"
                  >
                    <div class="onxia">
                      <span>年份</span>
                      <span>Year</span>
                    </div>
                    <div class="bianhao">{{ vehicle.yearCode }}款</div>
                  </small>
                </div>
                <span
                  class="absolute top-0 right-0 z-10 flex items-center justify-center text-xs text-white tag"
                >
                  BUY
                </span>
              </a-card>
            </template>
          </div>
        </div>
      </template>
      <template v-else-if="showVideo && currentProduct">
        <div style="width: 100%; max-width: 100vw; overflow: hidden; overflow-y: auto">
          <!-- 如果 vehicleType 是 'left'左舵车，显示图片 -->
          <img
            v-if="vehicleType === 'left'"
            :src="decodeURIComponent(currentProduct.text) + '?t=' + Date.now()"
            style="width: 100%; height: auto"
          />

          <!-- 否则，如果 vehicleType 是 'right'右舵车，显示视频 -->
          <video v-else controls style="width: 100%; height: 100%">
            <source
              :src="decodeURIComponent(currentProduct.text) + '?t=' + Date.now()"
              type="video/mp4"
            />
            Your browser does not support the video tag.
          </video>
        </div>
      </template>
      <template v-else>
        <div class="nuna">
          <p>该车型暂无数据</p>
        </div>
      </template>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.content-placeholder {
  :deep(img) {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.bg-black.opacity-50 {
  background-color: rgba(0, 0, 0, 0.5);
}
.nuna {
  width: 100%;
  max-width: 100vw;
  overflow: hidden;
  overflow-y: auto;
  margin-left: 50px;
  margin-top: 50px;
  font-size: 18px;
}
.limited-text {
  display: flex;
  margin-left: 20px;
  padding: 0px 20px 0px 20px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px solid rgba(0, 0, 0, 0.02);
  border-radius: 5px;
  border-color: #d9d9d9;
}
.swiper-slide {
  width: calc(26% - 2.5rem) !important;
  padding: 0.1rem;
  height: 18rem;
}

.aimage {
  height: 5rem;
  width: 3rem;
  object-fit: fill; // 保持图片的比例，可能会裁剪图片
}
.widtts {
  margin-top: 1.5rem;
  width: 14rem;
  white-space: nowrap; /* 防止文本换行 */
  padding: 0 0.8rem; /* 添加一些内边距，以确保内容不会紧贴边缘 */
  box-sizing: border-box; /* 确保内边距不会增加元素的宽度 */
}
.productc {
  height: 45px;
  margin-top: 10px;
  row-gap: 1rem;
}
.leftcon {
  // padding-right: 3rem;
}
.leftlxx {
  margin-left: 30px;
  display: flex;
  flex-direction: column;
  height: 43px;
  align-items: center;
  font-size: 14px;
}
.bianhao {
  display: flex;
  align-items: center;
  margin-left: 0.7rem;
  color: rgba(0, 0, 0, 0.88);
  font-size: 1.2rem;
}
.onxia {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  color: rgba(0, 0, 0, 0.88);
}
.pxma {
  position: relative;
  padding-left: 1rem;
  padding-right: 50rem;
}
</style>
